<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\admin;
use App\Exception\ValidateException;
use App\Controller\AbstractController;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Router\Dispatched;


class CommonController extends AbstractController
{
	
	
	public function beforeAction(){
	    if($this->request->getAttribute(Dispatched::class)->isFound()){
			$route = $this->request->getAttribute(Dispatched::class)->handler->callback;
			$action = $route[1];
			
			$sign_status = session()->get('admin_auth_sign') == data_auth_sign(object2array(session()->get('admin')),config('my.password_secrect')) ? true : false;
		
			if(!$sign_status && !$this->request->is(config('app.app_map.admin','admin').'/Login/*')){
				return '<script type="text/javascript">top.parent.frames.location.href="/'.config('app.app_map.admin','admin').'/Login/login";</script>';
			}
			
			if($sign_status){				
				$newnodes = [];
				if(session()->get('admin')->access){
					foreach(session()->get('admin')->access as $key=>$val){
						$newnodes[] = str_replace('admin',config('app.app_map.admin','admin'),parse_url($val)['path']);
					}
				}
				
				$white = [];
				if(config('my.nocheck')){
					foreach(config('my.nocheck') as $k=>$v){
						$white[] = str_replace('admin',config('app.app_map.admin','admin'),$v);
					}
				}
				
				$url = '/'.$this->request->path();
				if(session()->get('admin')->role_id <> 1 && !in_array($url,$white) && !in_array($action,['getFieldList','getInfo'])){	
					if(!in_array($url,$newnodes)){
						throw new ValidateException("你没有权限访问!");
					}
				}
				
				$event['username'] = session()->get('admin')->username;
				$event['application_name'] = 'admin';
				
				event(new \App\Event\DoLogEvent($event));
			}
		}
		
	}
	
    
	//格式化sql字段查询 转化为 key=>val 结构
	protected function query($sql,$connect='mysql'){
		preg_match_all('/select(.*)from/iUs',$sql,$all);
		if(!empty($all[1][0])){
			$sqlvalue = explode(',',trim($all[1][0]));
		}
		if(strpos($sql,'tkey') !== false){
			$sqlvalue[1] = 'tkey';
		}
		
		if(strpos($sql,'tval') !== false){
			$sqlvalue[0] = 'tval';
		}
		$sql = str_replace('pre_',config('databases.'.$connect.'.prefix'),$sql);
		$list = Db::connection($connect)->select($sql);
		$list = object2array($list);
		$array = [];
		foreach($list as $k=>$v){
			$array[$k]['key'] = $v[$sqlvalue[1]];
			$array[$k]['val'] = $v[$sqlvalue[0]];
			if(isset($sqlvalue[2]) && $sqlvalue[2]){
				$array[$k]['pid'] = $v[$sqlvalue[2]];
			}
		}
		return $array;
	}
	

	
}
